package service

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"github.com/pkg/errors"
	"sync"
)

type UserClient struct {
	Web *websocket.Conn
	App *websocket.Conn
}

const App = "app"
const Web = "web"

var (
	clients   = make(map[int]*UserClient) // 已连接的客户端
	clientsMu sync.Mutex                  // 保护clients的互斥锁
)

func UserOnline(userId int, c *websocket.Conn, clientType string) {
	_ = GetUserConn(userId, clientType)
	clientsMu.Lock()
	defer clientsMu.Unlock()
	cli := clients[userId]
	if clientType == App {
		cli.App = c
	} else {
		cli.Web = c
	}
}

func UserOffline(userId int, clientType string) {
	_ = GetUserConn(userId, clientType)
	clientsMu.Lock()
	defer clientsMu.Unlock()
	cli := clients[userId]
	if clientType == App {
		cli.App = nil
	} else {
		cli.Web = nil
	}
}

func GetUserConn(userID int, clientType string) *websocket.Conn {
	clientsMu.Lock()
	defer clientsMu.Unlock()
	_, ok := clients[userID]
	if !ok {
		clients[userID] = &UserClient{}
	}
	if clientType == App {
		return clients[userID].App
	} else {
		return clients[userID].Web
	}
}

func SendUserMsg(userID int, content, clientType, operate string) error {
	data := map[string]interface{}{
		"content": content,
		"operate": operate,
	}

	bytes, _ := json.Marshal(data)

	if conn := GetUserConn(userID, clientType); conn != nil {
		return conn.WriteMessage(websocket.TextMessage, bytes)
	} else {
		return errors.New("客户端不在线")
	}
}
